判断List集合中对象的某个字段是否存在重复值

判断泛型集合中的对象的某个字段是否有重复值的需求,特在此对方法进行记录。
这里我们使用了Java8的新特性Strem流,详细代码如下。
实体类如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**  
* @Title: Person.java
* @Description: TODO(描述)
* @author Soul
*/
public class Person {

private String name;
private Integer age;
private String gradle;

public Person() {
super();
}

public Person(String name, Integer age, String gradle) {
super();
this.name = name;
this.age = age;
this.gradle = gradle;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGradle() {
return gradle;
}
public void setGradle(String gradle) {
this.gradle = gradle;
}

@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", gradle=" + gradle + "]";
}

}

测试代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static void main(String[] args) {
Person person1 = new Person("小刘", 24, "男");
Person person2 = new Person("小贺", 18, "女");
Person person3 = new Person("小袁", 18, "女");
Person person4 = new Person("小李", 21, "男");
Person person5 = new Person("小子", 21, "男");
List<Person> persons = Arrays.asList(person1, person2, person3, person4,person5);

// 根据指定属性分组,并统计数量(key:指定属性,value:数量)

Map<Object, Long> mapGroup = persons.stream().collect(Collectors.groupingBy(person -> person.getAge(), Collectors.counting()));
System.out.println(mapGroup.toString());

// 筛选Map中value大于1的key
Stream<Object> stringStream = mapGroup.entrySet().stream().filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey());
System.out.print("重复的数据:{ ");
stringStream.forEach(str -> {
System.out.print(str + " ");
});
System.out.println("}");
}

输出结果:

1
2
{18=2.21=2,24=1}
重复的数据:{ 18 21 }
继开 wechat
欢迎加我的微信,共同交流技术